package com.gongpingjialoan.utility;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class LocationDecoder {

	//TODO 版本发布时修改为Release-Key(同时修改的还有AndroidManifest.xml 文件)
	//	String key = "1tMhjRHbVOdAILSvjqFZz7FI";	//debug.keystore
	String key = "nkKDzjXXjGWyvlGu62KpDvGA";	//android.keystore

	public String getCityName(String latValue, String longValue) {
		return getCityFromJson(getLocationJson(latValue, longValue));
	}
	
	public String getProvinceName(String latValue, String longValue) {
		return getProvinceFromJson(getLocationJson(latValue, longValue));
	}
	
	public JSONObject getLocationJson(String latValue, String longValue){

		String urlStr = "http://api.map.baidu.com/geocoder?location=" + latValue + "," + longValue + "&output=json&key=" + key;
		HttpClient httpClient = new DefaultHttpClient();
		StringBuilder builder = new StringBuilder();
		JSONObject jsonObject = null;
		String status = "failed";
		try{
			HttpResponse response = httpClient.execute(new HttpGet(urlStr));
			BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
				builder.append(s);
			}
			jsonObject = new JSONObject(builder.toString());
			status = jsonObject.getString("status");
			if (!status.equals("OK")) {
				return null;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return jsonObject;
	}

	static public String getCityFromJson(JSONObject jsonObject) {
		try {
			if (null == jsonObject) {
				return null;
			}
			JSONObject result = jsonObject.getJSONObject("result");

			if (null == result) {
				return null;
			}
			JSONObject adrComponent = result.getJSONObject("addressComponent");

			if (null == adrComponent) {
				return null;
			}
			return adrComponent.getString("city");

		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	static public String getProvinceFromJson(JSONObject jsonObject) {
		try {
			if (null == jsonObject) {
				return null;
			}
			JSONObject result = jsonObject.getJSONObject("result");

			if (null == result) {
				return null;
			}
			JSONObject adrComponent = result.getJSONObject("addressComponent");

			if (null == adrComponent) {
				return null;
			}
			return adrComponent.getString("province");

		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	public interface OnLocationNameIn {
		void onNameIn(String locationName);
	}

}